<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Zhuzhichao\IpLocationZh\Ip;

class LoginController extends Controller {

    public function __construct() {
        $this->middleware('guest')->except('logout');
    }

    public function username() {
        return 'username';
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index() {
        return view('admin.login');
    }

    /**
     * @param Request $request
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function validateLogin(Request $request) {
        $this->validate($request, [
            'password' => 'required',
            'captcha'  => 'required|captcha',
        ], [
            'captcha.required' => '验证码不能为空',
            'captcha.captcha'  => '请输入正确的验证码',
        ]);
    }

    public function login(Request $request) {
        $inputs = $request->only('username', 'password');
        $guard = $this->getGuard();
        $IP = $request->getClientIp();
        $address = implode(" - ", array_filter(Ip::find($IP)));

        $this->validateLogin($request);

        if ($guard->attempt($inputs)) { // 登录成功
            $user = $guard->user();
            $user->logintime = date('Y-m-d H:i:s', time());
            $user->loginip = $IP;
            $user->address = $address;
            $user->save();

            $result = [
                'code' => 0,
                'data' => [
                    'username' => 1,
                    'password' => 2,
                    'redirect'   => session('url.intended'),
                ],
            ];
            session()->forget('url.intended');
        } else { //登录失败(用户名或密码错误)
            $result = [
                'code' => 1,
                'data' => [
                    'username' => $inputs['username'],
                    'password' => $inputs['password'],
                ],
                'msg'  => '用户名密码不正确',
            ];
        }

        return response()->json($result);
    }

    private function getGuard() {
        return Auth::guard();
    }

    public function logout(Request $request) {
        Auth::logout();

        return redirect('/admin/login');
    }
}
